/*
 * caijie 2014.3
 * 分段文件
 */
package com.fg114.main.util;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.Serializable;

import org.json.JSONException;
import org.json.JSONObject;

public class FileAccessI implements Serializable{
	private final String myfileName = "hi.mp3";
	RandomAccessFile oSavedFile;
	long nPos;
	
	public FileAccessI() throws IOException{
		this("", 0);
	}
	
	public FileAccessI(String sName, long nPos) throws IOException{
		oSavedFile = new RandomAccessFile(sName, "rw");
		this.nPos = nPos;
		oSavedFile.seek(nPos);
	}
	
	public synchronized int write(byte[] b, int nStart, int nLen){
		int n=-1;
		try{
			oSavedFile.write(b,nStart,nLen);
			n=nLen;
			
		}catch(IOException e){
			e.printStackTrace();
		}
		
		return n;
	}
	
	//每次读取字节
	public synchronized Detail getContent(long nStart, int len){
		Detail detail= new Detail();
		detail.b = new byte[len];
		
		try{
			oSavedFile.seek(nStart);
			detail.length = oSavedFile.read(detail.b);
		}catch(IOException e){
			e.printStackTrace();
		}
		
		return detail;
	}
	
	//分段包内容
	public class Detail{
		public byte[] b;
		public int length;
	}
	
	//获取文件长度
	public long getFileLength(){
		Long length = 0L;
		try{
			length = oSavedFile.length();
		}catch(IOException e){
			e.printStackTrace();
		}
		
		return length;
	}
	
	public void closeFile(){
		try {
			oSavedFile.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
